// 分类模块
import { topCategory } from '@/api/constants'
import { findAllCategory } from '@/api/home'

const state = () => {
  return {
    // 分类信息
    categoryList: topCategory.map((item) => ({ name: item }))
  }
}
const mutations = {
  // 修改分类
  setCategory(state, payload) {
    state.categoryList = payload
  },
  // 显示二级分类
  show(state, id) {
    const currentCategory = state.categoryList.find((item) => item.id === id)
    currentCategory.open = true
  },
  // 隐藏二级分类
  hide(state, id) {
    const currentCategory = state.categoryList.find((item) => item.id === id)
    currentCategory.open = false
  }
}
const actions = {
  // 获取分类
  async getCategory({ commit }) {
    const { result } = await findAllCategory()
    // 点击一级分类不会关闭二级分类 因此添加open来控制
    result.forEach((item) => (item.open = false))
    commit('setCategory', result)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
